import { tencentAK } from '../../common/const.js'
import { map } from '../../data/data';
import { format } from '../../utils/dateUtil.js';
import { myGetRequest, myPostRequest } from "../../utils/myRequest.js"
var consoleUtil = require('../../utils/consoleUtil.js');
var dateUtil = require('../../utils/dateUtil.js');
var mapService = require('../../service/mapService.js');
var QQMapWX = require('../../lib/qqmap-wx-jssdk.js');
let scenicList = require('../../data/data');
//index.js
//获取应用实例
const app = getApp();
const defaultScale = 14;

//定义全局变量
var totalMarker = [];
var curId = 1;
let includePointsData = [];
let long = 0;  //已完成景点数量
//ui相关
var bottomHeight = 0;
var windowHeight = 0;
var windowWidth = 0;
//Map组件
var mapId = 'myMap';
var qqmapsdk;
Page({
  data: {
    userInfo: {},
    showSignStart:true,
    //当前景点是否以及完成打卡
    isDone: false,
    //marker弹窗
    showDialog:false,
    scenicName:"",
    scenicIntroduction:"",
    Introduction:"",
    image:"",
    //默认坐标
    longitude: '120.414721',
    latitude: '36.072530',
    //地图缩放级别
    scale: defaultScale,
    markers: [],
    showUpload: true,
    //运动路线
    polyline: [],
    //发生给服务器的位置数据
    traceList: [],
    //地图高度
    mapHeight: 0,
    selectAddress: '',
    centerLongitude: '',
    centerLatitude: '',
    currentMarkerId: 0,
    completeList: [],
    status:'',
    finishDate:"",
  },

  onLoad:  function (options) {
    var that = this;
    console.log("页面初始化");
    console.log(scenicList[0]);
    var userInfo;
    try {
       userInfo = wx.getStorageSync('userInfo');
      if (!userInfo) {
        wx.redirectTo({
          url: '../login/login'
        })
      }
    } catch (e) {
      // Do something when catch error
      console.log("页面初始化失败： "+e)
    }
          that.setData({
            userInfo : userInfo,  
          })
    //检测更新
    mapService.checkUpdate();
    //定位权限校验
    mapService.scopeSetting(that);
  },

  onShow: async function () {
    consoleUtil.log('onShow--------------------->');
    var that = this;
    that.changeMapHeight();
    //设置上传按钮的布局
    //如果刚从选择地址页面带数据回调回来，则显示选择的地址
    that.getCenterLocation();
    //请求地理位置信息,移动中心点坐标
    //mapService.requestLocation(that);

    const res= await myGetRequest({url:"/complete/findComplete?userId="+that.data.userInfo.id});

    if( res.statusCode == 200 ){   
      if(res.data.code==0){
          long = res.data.data.length // 计数 

          that.setData({
              completeList:res.data.data,  
            })
            console.log("打印完成列------")
            console.log(that.data.completeList)
        }else{
        console.log(res.data.message);
        wx.showToast({
          title: res.data.message,
          icon: 'none',
          duration:2500
        }) 
      }
    }else{
      wx.showToast({
        title: '网络错误！',
        icon: 'error',
        duration:1500
      }) 
    }


    that.queryMarkerInfo();
  },

  /**
   * 页面不可见时
   */
  onHide: function () {

  },
  //页面初始化时设置地图高度
  changeMapHeight: function () {
    var that = this;
    var count = 0;
    wx.getSystemInfo({
      success: function (res) {
        consoleUtil.log('页面初始化时设置地图高度' + res);
        windowHeight = res.windowHeight;
        windowWidth = res.windowWidth;

        that.setMapHeight();
      },
    })
  },

  setMapHeight: function (params) {
    var that = this;
    that.setData({
      mapHeight: (windowHeight - bottomHeight) + 'px'
    })

  },
  //--------------------UI设置end---------------------

  /** 
   * 初始化地图
   */
  initMap: function () {
    var that = this;
    qqmapsdk = new QQMapWX({
      key: tencentAK
    });
    that.getCenterLocation();
  },


  /**
   * 更新上传坐标点
   */
  updateCenterLocation: function (latitude, longitude) {
    var that = this;
    that.setData({
      centerLatitude: latitude,
      centerLongitude: longitude
    })
  },

  /**
   * 回到定位点
   */
  selfLocationClick: function () {
    var that = this;
    //还原默认缩放级别
    that.setData({
      scale: defaultScale
    })
    //必须请求定位，改变中心点坐标
    mapService.requestLocation(that);
  },

  /**
   * 移动到中心点
   */
  moveTolocation: function () {
    var mapCtx = wx.createMapContext(mapId);
    mapCtx.moveToLocation();
  },


  /**
   * 点击控件时触发
   */
  controlTap: function () {

  },

  /**
   * 点击地图时触发
   */
  bindMapTap: function () {
    //恢复到原始页
    this.adjustViewStatus(true);
  },

  adjustViewStatus: function (uploadStatus) {
    var that = this;
    that.setData({
      //显示marker
      //showDialog: uploadStatus,
    })
    that.changeMapHeight();
  },

  onShareAppMessage: function (res) {

  },

  /**
   * 拖动地图时回调
   * 视野发生变化时触发
   */
  regionChange: function (res) {
    var that = this;
    // 改变中心点位置  
    if (res.type == "end") {
      that.getCenterLocation();
    }
  },

  /**
   * 得到中心点坐标
   */
  getCenterLocation: function () {
    var that = this;
    var mapCtx = wx.createMapContext(mapId);
    mapCtx.getCenterLocation({
      success: function (res) {
        that.updateCenterLocation(res.latitude, res.longitude);
        //逆地址解析
        //mapService.regeocodingAddress(that,qqmapsdk);
        //that.queryMarkerInfo();
      }
    })
  },
  //-----------------------Marker相关处理逻辑------------------------
  /**
   * 查询 marker 信息
   * 初始化的时候调用
   */
  queryMarkerInfo: function () {
    var that = this;
    consoleUtil.log('查询当前坐标 marker 点信息')
    //调用请求 marker 点的接口就好了
    totalMarker=[];
    // for (let item of scenicList) {
    //   console.log(item);
    //   let marker = that.createInitMarker(item);
    //   totalMarker.push(marker);
    // }

    console.log("completeList-------");
    var list=that.data.completeList;
    console.log(list);
    if(list.length==0){
        wx.showToast({
            title: '用户未景点打卡',
            icon: 'error',
        })
    }else{
    for (let item of list) {    
        console.log(item);
        console.log(scenicList[item.routeId-1]);
        let marker = that.createInitMarker(scenicList[item.routeId-1]);
        totalMarker.push(marker);
      }

    consoleUtil.log('-----------------------');
    consoleUtil.log('初始化marker' + totalMarker);
    that.setData({
      markers: totalMarker
    })
    var mapCtx1 = wx.createMapContext(mapId);
    // 显示所有标记点
  mapCtx1.includePoints({
  padding: [20],
  points: includePointsData //放入所有坐标轴的数组   并引用此方法
})
    }
  },
  /**
   * 
   * 点击marker
   */
  bindMakertap: async function (e) {
    var that = this;
    curId = e.markerId
    console.log('点击了：Marker '+this.data.markers);
    console.log(e)
    console.log(that.data.completeList)
    for(let item of that.data.completeList){
        if(curId==item.routeId){
            that.setData({
            status:item.state,
            finishDate:dateUtil.formatTime(item.endDate, 'YY-MM-DD')
            })
        }
    }

    console.log(that.data.finishDate)
    console.log(that.data.status)
    // var name = this.data.markers[curId - 1].name
    var name = scenicList[curId - 1].name
    console.log('点击了：Marker '+name);
    // console.log(this.data.markers[curId - 1])
    //重新设置点击marker为中心点
    //   var marker = that.data.markers[curId - 1];
      var marker = scenicList[curId - 1];
        var isDone =await that.isDone(marker.id, that.data.userInfo.id)
         that.setData({
          longitude: scenicList[curId - 1].endLong,
          latitude: scenicList[curId - 1].endLat,
          scenicIntroduction:marker.Introduction,
          scenicName:marker.name,
          image:marker.image,
          showDialog:true,
          isDone : isDone
        })
        console.log(marker.name+"是否完成："+that.data.isDone)
    
  },
  toggleDialog: function () {
    this.setData({
      showDialog: false,
    })
  },
  /**
   * 创建marker
   */
  createInitMarker: function (point) {
    let latitude = point.endLat;
    let longitude = point.endLong;

    includePointsData.push(
      {
        latitude: latitude,
        longitude:longitude
      }
    )
    let marker = {
      iconPath: point.iconUrl,
      id: point.id || 0,
      name: point.name || '',
      latitude: latitude,
      longitude: longitude,
      width: 30,
      height: 30,
      
                      //景点简介
                      Introduction: point.Introduction,
                      //景点路线
                      routeId: point.routeId,
                      //beginLat
                      beginLat: point.beginLat,
                      beginLong: point.beginLong,
                      //简介照片
                      image:point.image,
      label: {
        content: point.name,
        color: '#0081ff',
        fontSize: 8,
        bgColor: "#fff",
        borderRadius: 30,
        borderColor: "#0081ff",
        borderWidth: 1,
        padding: 3,
        textAlign:"center"
      },
      callout: {
        content: point.name,
        fontSize: 0,
      }
    };
    return marker;
  },
 

//--------------------------------
  /**
   * 
   * @returns 这个景点否已经完成
   */
   isDone: async function (scenicId, userId) {
    var that = this
    const res = await myGetRequest({url:"/complete/isDone/" + scenicId+"/"+userId});
    if( res.statusCode == 200 ){   
      if(res.data.code==0){
        var isDone =res.data.data;
         return isDone;
        }else{
        console.log(res.data.message);
        wx.showToast({
          title: res.data.message,
          icon: 'none',
          duration:2500
        })
        return false;
      }
    }else{
      wx.showToast({
        title: '网络错误！',
        icon: 'error',
        duration:1500
      })
      return false;
    }
  },
})
